package com.kuanter.kuanterauto.message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.database.DBManager;
import com.kuanter.kuanterauto.entity.MessageInfo;
import com.umeng.analytics.MobclickAgent;

/**
 * @author soup
 * 
 */
public class MessageListActivity extends BaseActivity_NoBar {
	public ArrayList<String> msgDate;
	public HashMap<String, Object> msgListMap;
	private DBManager mgr;
	private List<MessageInfo> messageInfos=null;

	public MessageListActivity() {
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.message);
		if(getIntent().getExtras()!=null){
			messageInfos=(List<MessageInfo>) getIntent().getExtras().getSerializable(MessageInfo.TAG);
		}

		msgListMap = new HashMap<String, Object>();
		msgDate = new ArrayList<String>();

		// 初始化DBManager
		mgr = new DBManager(this);

		//打开或创建test.db数据库  
        SQLiteDatabase db = openOrCreateDatabase("message.db", Context.MODE_PRIVATE, null);  
//        db.execSQL("DROP TABLE IF EXISTS message"); 
//      //创建message表  
//        db.execSQL("CREATE TABLE message (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content TEXT, pushTime VARCHAR)");  
     
        
        
        
        query();
		if (msgListMap.isEmpty()) 
		{
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("title", "欢迎使用宽途汽车");
			map.put("content",
					"通过宽途汽车官方APP，可以迅速查询到符合您设置条件的宽途服务网点，并提供网点忙碌程度及去到网点的便捷路线；同时，您可以清晰管理个人信息、随时查询消费记录、获知宽途最新服务优惠通知。");
			map.put("pushTime", "2013-04-01 00:00");
			ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			list.add(map);
			msgDate.add("2012年04月01日");
			msgListMap.put(msgDate.get(0), list);
			
			
	        //插入数据  
	        db.execSQL("INSERT INTO message VALUES (NULL, ?, ?, ?)", new Object[]{map.get("title"), map.get("content"),map.get("pushTime")});
	        
	        
		}
		//关闭当前数据库  
        db.close(); 
	     
//        MessageInfo mss = new MessageInfo();
//        mss.setTitle("5");
//        mss.setContent("test content");
//        mss.setPushTime("2013-01-03 13-33-00");
//        ArrayList<MessageInfo> tmplist = new ArrayList<MessageInfo>();
//        tmplist.add(mss);
//        add(tmplist);
        
        if(messageInfos != null){
        	add(messageInfos);
        }
        
        
        
	        
		final ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
			// 设置组视图的显示文字

			// 重写ExpandableListAdapter中的各个方法
			@Override
			public int getGroupCount() {
				return msgDate.size();
			}

			@Override
			public Object getGroup(int groupPosition) {
				return msgDate.get(groupPosition);
			}

			@Override
			public long getGroupId(int groupPosition) {
				return groupPosition;
			}

			@Override
			public int getChildrenCount(int groupPosition) {
				ArrayList<HashMap<String, String>> temp_list = (ArrayList<HashMap<String, String>>) msgListMap
						.get(msgDate.get(groupPosition));
				return temp_list.size();
			}

			@Override
			public Object getChild(int groupPosition, int childPosition) {
				ArrayList<HashMap<String, String>> temp_list = (ArrayList<HashMap<String, String>>) msgListMap
						.get(msgDate.get(groupPosition));
				HashMap<String, String> map = temp_list.get(childPosition);

				return map;
			}

			@Override
			public long getChildId(int groupPosition, int childPosition) {
				return childPosition;
			}

			@Override
			public boolean hasStableIds() {
				return true;
			}

			@Override
			public View getGroupView(int groupPosition, boolean isExpanded,
					View convertView, ViewGroup parent) {
				View v = LayoutInflater.from(MessageListActivity.this).inflate(
						R.layout.message_date, null);

				TextView textView = (TextView) v.findViewById(R.id.tv_msg_date);
				textView.setText(getGroup(groupPosition).toString());
				textView.setGravity(Gravity.CENTER);
				textView.setTextSize(11);
				return v;
			}

			@Override
			public View getChildView(int groupPosition, int childPosition,
					boolean isLastChild, View convertView, ViewGroup parent) {

				View v = LayoutInflater.from(MessageListActivity.this).inflate(
						R.layout.message_item, null);

				TextView textView = (TextView) v
						.findViewById(R.id.tv_msg_title);
				HashMap<String, String> map = (HashMap<String, String>) getChild(
						groupPosition, childPosition);
				TextPaint paint = textView.getPaint();  
				paint.setFakeBoldText(true);
				textView.setText(map.get("title"));

				TextView textView2 = (TextView) v
						.findViewById(R.id.tv_msg_time);
				textView2.setText(map.get("pushTime").substring(11,
						map.get("pushTime").length()));
				
				TextView textView3 = (TextView) v
						.findViewById(R.id.tv_msg_content);
				textView3.setText(map.get("content"));

				return v;
			}

			@Override
			public boolean isChildSelectable(int groupPosition,
					int childPosition) {
				return true;
			}

		};

		ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandableListView_messageList);
		expandableListView.setAdapter(adapter);
		// 默认全部展开
		int groupCount = expandableListView.getCount();
		for (int i = 0; i < groupCount; i++) {
			expandableListView.expandGroup(i);
		}
		;
		expandableListView.setGroupIndicator(null);

		// 设置item点击的监听器
		expandableListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {

				HashMap<String, String> map = (HashMap<String, String>) adapter
						.getChild(groupPosition, childPosition);

				Bundle bundle = new Bundle();
				bundle.putString("title", map.get("title"));
				bundle.putString("content", map.get("content"));
				qStartActivity(MessageDetailActivity.class, bundle);
				return false;
			}
		});

		expandableListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) { //

				return true;

			}

		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 应用的最后一个Activity关闭时应释放DB
		mgr.closeDB();
	}
	
	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	public void readHistoryMessageInfo() {

	}

	public void writeHistoryMessageInfo() {

	}

	public void add(List<MessageInfo> messages) {

		mgr.add(messages);
		query();
	}

	public void query() {

		List<MessageInfo> messages = mgr.query();
		msgListMap.clear();
		msgDate.clear();
		for (MessageInfo message : messages) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("title", message.getTitle());
			map.put("content", message.getContent());
			map.put("pushTime", message.getPushTime());
			
			String date = message.getPushTime().substring(0, 4) + "年"
					+ message.getPushTime().substring(5, 7) + "月"
					+ message.getPushTime().substring(8, 10) + "日";
			if(msgDate.contains(date))
			{
				ArrayList<HashMap<String, String>> list = (ArrayList<HashMap<String, String>>) msgListMap.get(date);
				list.add(map);
				msgListMap.put(date, list);
			}
			else
			{
				ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
				msgDate.add(date);
				list.add(map);
				msgListMap.put(date, list);
			}
			
		}
		
		

	}

}
